/**
 *
 * @author Kassio Kiarelly Soares de Oliveira <kassiokiarelly@gmail.com>
 * @author Pablo Veinberg <pveinberg@gmail.com>
 */
package Visao;

import Modelo.Reserva;
import RMI.ServicosCliente;
import RMI.ServicosIF;
import Util.Utils;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class GridReservas extends javax.swing.JDialog {

    private ServicosIF sc = ServicosCliente.getInstance();
    private Reserva r;

    public GridReservas() throws RemoteException {
        initComponents();
        setLocationRelativeTo(null);
    }

    public void popularGrid(List<Reserva> reservas) throws RemoteException {

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        if (reservas == null) {
            reservas = sc.getReservas();
        }

        try {

            DefaultTableModel modelo = (DefaultTableModel) grid.getModel();
            modelo.setNumRows(0);
            if (reservas.size() > 0) {
                for (Reserva res : reservas) {
                    modelo.addRow(new Object[]{res.getId(), res.getHospede().getNome(), res.getHotel().getNome(),
                                res.getQuarto().getNumero(), sdf.format(res.getInicio()),
                                sdf.format(res.getFim()), getStatus(res.getQuarto().isOcupado()) ,res.getTotalHospedagem()});
                }
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar ao servidor.");
        }

    }

    private String getStatus(boolean status) {
        return (status == true) ? "Ocupado" : "Disponível"; 
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        grid = new javax.swing.JTable();
        btNovo = new javax.swing.JButton();
        btEditar = new javax.swing.JButton();
        anularReserva = new javax.swing.JButton();
        btnCheckIn = new javax.swing.JButton();
        checkOut = new javax.swing.JButton();
        atualizar = new javax.swing.JButton();

        setTitle("Reservas");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        grid.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Hospede", "Hotel", "Quarto", "Check in", "Check out", "Status", "Saldo"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        grid.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(grid);

        btNovo.setText("Nova Reserva");
        btNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoActionPerformed(evt);
            }
        });

        btEditar.setActionCommand("Extender Reserva");
        btEditar.setLabel("Extender Reserva");
        btEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEditarActionPerformed(evt);
            }
        });

        anularReserva.setText("Anular Reserva");
        anularReserva.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                anularReservaActionPerformed(evt);
            }
        });

        btnCheckIn.setText("Check In");
        btnCheckIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCheckInActionPerformed(evt);
            }
        });

        checkOut.setText("Check Out");
        checkOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkOutActionPerformed(evt);
            }
        });

        atualizar.setText("Atualizar");
        atualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                atualizarActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(btnCheckIn)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(checkOut)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 236, Short.MAX_VALUE)
                        .add(atualizar)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(anularReserva)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btEditar)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btNovo))
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 820, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(29, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(16, 16, 16)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 258, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnCheckIn)
                    .add(checkOut)
                    .add(btNovo)
                    .add(btEditar)
                    .add(anularReserva)
                    .add(atualizar))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        try {
            popularGrid(null);
        } catch (RemoteException ex) {
            Logger.getLogger(GridReservas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formWindowOpened

    private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoActionPerformed
        new FormReserva().setVisible(true);
        try {
            popularGrid(null);
        } catch (RemoteException ex) {
            Logger.getLogger(GridReservas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btNovoActionPerformed

    private void btEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEditarActionPerformed

        r = null;
        int linha = grid.getSelectedRow();
        int id = 0;
        if (linha >= 0) {
            id = (Integer) grid.getModel().getValueAt(linha, 0);
            try {
                r = ServicosCliente.getInstance().findReserva(id);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Erro ao tentar se comunicar com o servidor da aplicação.\n" + ex);
            }
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new FormReserva(r).setVisible(true);
                    popularGrid(null);
                } catch (RemoteException ex) {
                    Logger.getLogger(MenuPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

    }//GEN-LAST:event_btEditarActionPerformed

    private void anularReservaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_anularReservaActionPerformed


        r = null;
        int linha = grid.getSelectedRow();
        int id = 0;

        if (linha >= 0) {
            id = (Integer) grid.getModel().getValueAt(linha, 0);
            try {
                r = this.sc.findReserva(id);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Erro ao tentar se comunicar com o servidor da aplicação.\n" + ex);
            }
        }
        try {
            int result = this.sc.removeReserva(r);
            if (result == Utils.SUCESSO) {
                JOptionPane.showMessageDialog(null, "REserva anulada com sucesso.");
            }
        } catch (RemoteException ex) {
            Logger.getLogger(GridReservas.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            popularGrid(null);
        } catch (RemoteException ex) {
            Logger.getLogger(GridReservas.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_anularReservaActionPerformed

    private void btnCheckInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCheckInActionPerformed

        new FormCheckIn(getReservaDoGrid()).setVisible(true);
    }//GEN-LAST:event_btnCheckInActionPerformed

    private void checkOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkOutActionPerformed

        new FormCheckOut(getReservaDoGrid()).setVisible(true);
    }//GEN-LAST:event_checkOutActionPerformed

    private void atualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_atualizarActionPerformed
        try {
            popularGrid(null);
        } catch (RemoteException ex) {
            Logger.getLogger(GridReservas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_atualizarActionPerformed

    private Reserva getReservaDoGrid() {
        r = null;
        int linha = grid.getSelectedRow();
        int id = 0;
        if (linha >= 0) {
            id = (Integer) grid.getModel().getValueAt(linha, 0);
            try {
                r = ServicosCliente.getInstance().findReserva(id);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Erro ao tentar se comunicar com o servidor da aplicação.\n" + ex);
            }
        }
        return r;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton anularReserva;
    private javax.swing.JButton atualizar;
    private javax.swing.JButton btEditar;
    private javax.swing.JButton btNovo;
    private javax.swing.JButton btnCheckIn;
    private javax.swing.JButton checkOut;
    private javax.swing.JTable grid;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
